<template>
  <div>
    <!--    搜索框-->
    <div style="display:flex;justify-content: center;align-items: center;position: sticky;top: 54px;z-index: 100">
      <el-autocomplete ref="search"
                       v-model.trim="search.input" :fetch-suggestions="getSearchHistory" clearable
                       placeholder="请输入商品名称搜索商品"
                       style="width: 100%;margin: 10px 20px 30px 20px;border: 2px solid rgb(64,158,255);border-radius: 5px"
                       value-key="keyword"
                       @clear="clear" @select="searchSpu" @keyup.enter.native="searchSpu">
        <el-select slot="prepend" v-model="search.selection" style="width: 100px;line-height: inherit">
          <el-option label="商品" value="商品"></el-option>
          <el-option label="分类" value="分类"></el-option>
          <el-option label="品牌" value="品牌"></el-option>
        </el-select>
        <el-button slot="append" icon="el-icon-search" style="width: 80px"
                   @click="searchSpu"></el-button>
        <template slot-scope="{ item }">
          <div class="search-history-item" @mouseenter="search.hoveredItem = item"
               @mouseleave="search.hoveredItem = null">
            {{ item.keyword }}
            <i v-show="search.hoveredItem === item"
               class="el-icon-circle-close"
               @click.stop="removeSearchHistory(item.keyword)"/>
          </div>
        </template>
      </el-autocomplete>
    </div>
    <!--    分类__轮播图-->
    <el-row :gutter="10">
      <el-col :span="6">
        <el-card shadow="never" style="height: 40vh;background: rgb(242,251,255);">
          <div style="display: flex;flex-wrap: wrap">
            <div>
              <div style="padding: 0 0 10px 0; border-bottom: 2px solid #8bd8fc;
          font-size: 16px; font-weight:bold;color: rgba(49,177,239,0.88);margin-bottom: 10px">
                种类
              </div>
              <el-link v-for="cate in cateList" :key="cate.id"
                       style="margin:5px 5px;font-weight: normal;font-size: 14px;color: rgb(80,96,122)"
                       @click="clickCategory(cate)">
                {{ cate.name }}
              </el-link>
            </div>
            <div>
              <div style="padding: 0 0 10px 0; border-bottom: 2px solid rgba(255,133,188,0.88);
          font-size: 16px; font-weight:bold;color: rgba(255,133,188,0.88);margin: 10px auto">
                品牌
              </div>
              <el-link v-for="brand in brandList" :key="brand.id"
                       style="margin:5px 5px;font-weight: normal;font-size: 14px;color: rgb(80,96,122)"
                       @click="clickBrand(brand)">
                {{ brand.name }}
              </el-link>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col v-for="i in range(0,bannerList.length)" :key="i" :span="Math.floor(18/bannerList.length)">
        <el-carousel height="40vh" style="border-radius: 5px;box-shadow: 0 0 5px #555555" >
          <el-carousel-item v-for="item in bannerList[i]" :key="item.id">
            <el-image @click="goToSpu(item?.url)" :src="item.img" style="width:100%;height: 100%" fit="cover"></el-image>
          </el-carousel-item>
        </el-carousel>
      </el-col>
    </el-row>
    <!--    推荐商品    -->
    <!--    销量排行    -->
    <el-row :gutter="10" style="margin-top: 10px;display:flex">
      <el-col :span="18">
        <el-card shadow="never" style="height: 100%;background: rgb(255,242,245)">
          <div style="padding: 0 0 10px 0;margin-bottom: 10px; font-weight: bolder;
          border-bottom: 2px solid #f17092; font-size: 20px; color: #ff6565">
            推荐
          </div>
          <el-row :gutter="10">
            <el-col v-for="spu in recommend" :key="spu.id" :span="6">
              <SpuCard :spu="spu"/>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never" style="height: 100%;background: rgb(255,241,235)">
          <div style="padding: 0 0 10px 0; border-bottom: 2px solid #ff6200;
          font-size: 20px; font-weight:bold;color: #ff6200;margin-bottom: 10px">
            热销
          </div>
          <div v-for="(spu, index) in salesList" :key="spu.id"
               style="margin-bottom: 10px;cursor: pointer;display: flex;"
               @click="goodsDetail(spu)">
            <div style="display: flex;align-items: center;margin-right: 5px">
              <span :style="rankNumber(index)" style="margin-right: 10px">{{ index + 1 }}</span>
              <el-image :src="spu.urls" fit="cover" style="height: 80px;border-radius: 5px;aspect-ratio: 1 / 1;"></el-image>
            </div>
            <div style="display:flex;flex-direction: column;justify-content: space-between">
              <div class="spu-name" style="overflow: hidden; max-height: 34px; font-size: 12px">
                {{ spu.name }}
                {{ spu.detail ? spu.detail : '' }}
              </div>
              <div style="max-height: 40px;overflow: hidden">
                <el-tag effect="light"  v-for="value in getAttributeList(spu)" :key="value"
                        size="mini">{{ value }}
                </el-tag>
              </div>
              <div style="display: flex;justify-content: space-between">
                <span style="color:#ff6200;font-size: 18px;font-weight: bold"><span
                    style="font-size: 10px;font-weight: normal">￥</span>{{ spu.price }}
              </span>
                <span style="font-size: 12px;color: #ee6434">已售出{{
                    spu.sales < 100 ? spu.sales : Math.floor(spu.sales / 100) * 100
                  }}<span v-show="spu.sales>=100" style="font-size: 10px">+</span>双</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!--      全部商品，下拉加载更多-->
    <el-row :gutter="10" style="margin-top: 10px">
      <el-card shadow="never">
        <div style="padding: 0 0 10px 0;
        margin-bottom: 10px; font-weight: bolder;border-bottom: 2px solid #4bbbff;
        font-size: 20px; color: #33b0ff;display: flex;justify-content: center;align-items: center">
          全部商品
        </div>
        <el-row :gutter="10">
          <el-col v-for="spu in spuList" :key="spu.id" :span="5">
            <SpuCard :spu="spu"/>
          </el-col>
        </el-row>
      </el-card>
    </el-row>
  </div>
</template>

<script>
import {getAllBanner} from "@/api/banner";
import {getBrandList, getCateList, getGoodsSales, getRecommendedGoods, getSpuById, getSpuListFront} from "@/api/goods";
import {
  getHomeScroll,
  getSearchHistory,
  getUser,
  pushSearchHistory,
  removeSingleSearchHistory,
  setHomeScroll
} from "@/utils/storage";
import SpuCard from "@/components/common/SpuCard.vue";
import {range} from "lodash";

export default {
  name: "Home",
  components: {SpuCard},
  data() {
    return {
      search: {
        input: '',
        selection: '商品',
        hoveredItem: null,
      },
      salesList: [],
      cateList: [],
      brandList: [],
      recommend: [],
      bannerList: [[],[]],
      user: {},
      spuList: [],
      page: {
        pageNum: 1,
        pageSize: 8,
        total: 0
      }
    }
  },
  created() {
    this.user = getUser()
    this.load()
  },
  methods: {
    range,
    goToSpu(spuId){
      if (spuId === null || spuId === undefined || spuId === '') return
      getSpuById(spuId).then(res => {
        if (res.code === '0'){
          this.$store.commit('spu/setSelectedSpu',res.data)
          this.$router.push("/front/goods")
        }
      })
    },
    clear() {
      //由于vue数据异步更新，所以在清空input后，需要nextTick再执行聚焦操作从而展开完整的历史记录
      this.$nextTick(() => {
        this.$refs.search.getInput().blur()
        this.$refs.search.focus()
      })
    },
    getSearchHistory(keyword, callback) {
      callback(getSearchHistory(keyword))
    },
    saveSearchHistory() {
      pushSearchHistory({keyword: this.search.input, selection: this.search.selection})
    },
    removeSearchHistory(keyword) {
      removeSingleSearchHistory(keyword)
      this.$refs.search.suggestions = getSearchHistory()
    },
    searchSpu() {
      //保存历史记录
      this.saveSearchHistory()
      //跳转到Search页面
      this.$router.push({
        name: 'Search', params: {
          input: this.search.input,
          selection: this.search.selection
        }
      })
    },
    rankNumber(index) {
      if (index === 0)
        return {color: '#ff6200', fontWeight: 'bolder', fontSize: '18px'}
      if (index === 1)
        return {color: '#ffd060', fontWeight: 'bold', fontSize: '17px'}
      if (index === 2)
        return {color: '#989595', fontWeight: 'bold', fontSize: '16px'}
      return {color: '#c0c4cc', fontWeight: 'normal', fontSize: '15px'}
    },
    getAttributeList({attribute}){
      let list = []
      let keys = Object.keys(attribute)
      keys.forEach(key => {
        list = list.concat(attribute[key])
      })
      return list
    },
    goodsDetail(spu) {
      //使用vuex保存用户选中的spu
      this.$store.commit('spu/setSelectedSpu',spu)
      this.$router.push("/front/goods")
    },
    load() {
      getAllBanner().then(res => {
        if (res.code === '0') {
          const banners = res.data.filter(banner => !banner?.url?.startsWith('https://'))
          this.bannerList = [banners.slice(0, Math.floor(banners.length / 2)), banners.slice(Math.floor(banners.length / 2), banners.length)]
        }
      })
      getRecommendedGoods().then(res => {
        if (res.code === '0') {
          this.recommend = res.data.filter(spu => spu !== null).map(spu=>{
            let attr = JSON.parse(spu.attribute)
            if(!attr)
              attr = {}
            return {...spu,attribute:attr}
          })
        }
      })
      getGoodsSales().then(res => {
        if (res.code === '0') {
          this.salesList = res.data.map(spu=>{
            let attr = JSON.parse(spu.attribute)
            if(!attr)
              attr = {}
            return {...spu,attribute:attr}
          })
        }
      })
      getCateList().then(res => {
        if (res.code === '0') {
          this.cateList = res.data.map(category => {
            return {
              id: category.id,
              name: category.name
            }
          })
        }
      })
      getBrandList().then(res => {
        if (res.code === '0') {
          this.brandList = res.data.map(brand => {
            return {
              id: brand.id,
              name: brand.name
            }
          })
        }
      })
      getSpuListFront(this.search, this.page).then(res => {
        if (res.code === '0') {
          this.spuList = res.data.records
          this.page.total = res.data.total
        }
      })
    },
    clickCategory(cate) {
      this.search.input = cate.name
      this.search.selection = '分类'
      this.searchSpu()
    },
    clickBrand(brand) {
      this.search.input = brand.name
      this.search.selection = '品牌'
      this.searchSpu()
    },
    scrollToBottom() {
      if (this.spuList.length < this.page.total) {
        this.page.pageNum++
        getSpuListFront(this.search, this.page).then(res => {
          if (res.code === '0') {
            this.spuList = this.spuList.concat(res.data.records)
          }
        })
      }
    }
  },
  //实现用户返回主页后滚动保持在原来的位置,由于home开启了页面缓存，当从其他页面跳转回来时
  //会触发activated这个钩子
  activated(){
    const container = document.querySelector('.container')
    // console.log(container)
    if(container){
      const scrollTop = getHomeScroll()
      // console.log(scrollTop)
      if(scrollTop){
        container.scrollTop = Number(scrollTop)
      }
    }
  },
  beforeRouteLeave(to,from,next){
    const container = document.querySelector('.container')
    // console.log('set>>>',container.scrollTop)
    setHomeScroll(container.scrollTop)
    //重置滚动
    container.scrollTop = 0
    next()
  },
  beforeCreate(){
    //重置滚动
    setHomeScroll(0)
  }
};
</script>

<style scoped>
.search-history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px;
  cursor: pointer;
}

.home_container {
  margin-top: 20px;
}

.el-col-5 {
  width: 20%;
}

.spu-name {
  overflow: hidden;
  display: -webkit-box; /* 将对象作为弹性伸缩盒子模型显示 */
  -webkit-line-clamp: 2; /* 行数，值可以改，表示展示X行后多余的缩略展示 */
  -webkit-box-orient: vertical; /* 设置或检索伸缩盒对象的子元素的排列方式 */
  word-break: break-all;
  border: 1px solid #eef0f5;
}
</style>
